package com.example.s7;

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;

public class ClientExample {

    //private String endpointUrl = "opc.tcp://191.168.5.162:53530/OPCUA/SimulationServer";
    // 172.18.1.104
    private String endpointUrl = "opc.tcp://XmcWinCCServer:4862";
    private String username = "";
    private String password = "";

    public static void main(String[] args) throws Exception {
        ClientExample clientExample = new ClientExample();
        OpcUaClient client = clientExample.createClient();
        UaClient uaClient = client.connect().get(); //打开连接
        uaClient.disconnect().get(); //断开连接
    }

    public OpcUaClient createClient() throws UaException {
        return OpcUaClient.create(
                endpointUrl,
                endpointDescriptions -> {
                    final List<EndpointDescription> collect = endpointDescriptions.stream().collect(Collectors.toList());
                    final Optional<EndpointDescription> first = endpointDescriptions
                            .stream()
                            .findFirst();
                    System.out.println(first.get().getSecurityPolicyUri());
                    return Optional.of(collect.get(0));
                },
                configBuilder ->
                        configBuilder
                                .setApplicationName(LocalizedText.english("opc-ua client"))
                                .setApplicationUri(endpointUrl)
//                                .setIdentityProvider(new UsernameProvider(username, password))
                                .setIdentityProvider(new AnonymousProvider())
                                .setRequestTimeout(uint(5000))
                                .build()
        );
    }

}
